import request from '@/utils/request'

// 区域数据类型
export interface Area {
  id: number
  parentId: number | null
  name: string
  code: string
  level: number
  sort: number
  status: number
  remark?: string
  createTime: string
  updateTime: string
  children?: Area[]
  hasChildren?: boolean
  parentName?: string
}

// Mock数据库 - 模拟真实数据存储
let mockDatabase: Area[] = [
  {
    id: 1,
    parentId: null,
    name: '北京市',
    code: '110000',
    level: 1,
    sort: 1,
    status: 1,
    remark: '首都',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    parentName: '',
    hasChildren: true,
    children: [
      {
        id: 11,
        parentId: 1,
        name: '东城区',
        code: '110101',
        level: 2,
        sort: 1,
        status: 1,
        remark: '',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
        parentName: '北京市',
        hasChildren: true,
        children: [
          {
            id: 111,
            parentId: 11,
            name: '东华门街道',
            code: '110101001',
            level: 3,
            sort: 1,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '东城区',
            hasChildren: false,
            children: []
          },
          {
            id: 112,
            parentId: 11,
            name: '景山街道',
            code: '110101002',
            level: 3,
            sort: 2,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '东城区',
            hasChildren: false,
            children: []
          }
        ]
      },
      {
        id: 12,
        parentId: 1,
        name: '西城区',
        code: '110102',
        level: 2,
        sort: 2,
        status: 1,
        remark: '',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
        parentName: '北京市',
        hasChildren: true,
        children: [
          {
            id: 121,
            parentId: 12,
            name: '西长安街街道',
            code: '110102001',
            level: 3,
            sort: 1,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '西城区',
            hasChildren: false,
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 2,
    parentId: null,
    name: '上海市',
    code: '310000',
    level: 1,
    sort: 2,
    status: 1,
    remark: '直辖市',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    parentName: '',
    hasChildren: true,
    children: [
      {
        id: 21,
        parentId: 2,
        name: '黄浦区',
        code: '310101',
        level: 2,
        sort: 1,
        status: 1,
        remark: '',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
        parentName: '上海市',
        hasChildren: true,
        children: [
          {
            id: 211,
            parentId: 21,
            name: '南京东路街道',
            code: '310101001',
            level: 3,
            sort: 1,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '黄浦区',
            hasChildren: false,
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 3,
    parentId: null,
    name: '广东省',
    code: '440000',
    level: 1,
    sort: 3,
    status: 1,
    remark: '省份',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    parentName: '',
    hasChildren: true,
    children: [
      {
        id: 31,
        parentId: 3,
        name: '广州市',
        code: '440100',
        level: 2,
        sort: 1,
        status: 1,
        remark: '省会',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
        parentName: '广东省',
        hasChildren: true,
        children: [
          {
            id: 311,
            parentId: 31,
            name: '荔湾区',
            code: '440103',
            level: 3,
            sort: 1,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '广州市',
            hasChildren: false,
            children: []
          },
          {
            id: 312,
            parentId: 31,
            name: '越秀区',
            code: '440104',
            level: 3,
            sort: 2,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '广州市',
            hasChildren: false,
            children: []
          }
        ]
      },
      {
        id: 32,
        parentId: 3,
        name: '深圳市',
        code: '440300',
        level: 2,
        sort: 2,
        status: 1,
        remark: '特区',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00',
        parentName: '广东省',
        hasChildren: true,
        children: [
          {
            id: 321,
            parentId: 32,
            name: '罗湖区',
            code: '440303',
            level: 3,
            sort: 1,
            status: 1,
            remark: '',
            createTime: '2024-01-01 10:00:00',
            updateTime: '2024-01-01 10:00:00',
            parentName: '深圳市',
            hasChildren: false,
            children: []
          }
        ]
      }
    ]
  }
]

// 工具函数：扁平化树形数据
const flattenTree = (tree: Area[]): Area[] => {
  const result: Area[] = []
  
  const traverse = (nodes: Area[]) => {
    nodes.forEach(node => {
      const { children, ...nodeData } = node
      result.push(nodeData)
      if (children && children.length > 0) {
        traverse(children)
      }
    })
  }
  
  traverse(tree)
  return result
}

// 工具函数：查找区域
const findAreaById = (areas: Area[], id: number): Area | null => {
  for (const area of areas) {
    if (area.id === id) return area
    if (area.children && area.children.length > 0) {
      const found = findAreaById(area.children, id)
      if (found) return found
    }
  }
  return null
}

// 工具函数：删除区域及其子区域
const removeAreaById = (areas: Area[], id: number): Area[] => {
  return areas.filter(area => {
    if (area.id === id) return false
    if (area.children && area.children.length > 0) {
      area.children = removeAreaById(area.children, id)
    }
    return true
  })
}

// 工具函数：更新区域
const updateAreaById = (areas: Area[], id: number, updateData: Partial<Area>): Area[] => {
  return areas.map(area => {
    if (area.id === id) {
      return { ...area, ...updateData, updateTime: new Date().toLocaleString() }
    }
    if (area.children && area.children.length > 0) {
      area.children = updateAreaById(area.children, id, updateData)
    }
    return area
  })
}

// 工具函数：添加区域
const addArea = (areas: Area[], newArea: Area): Area[] => {
  if (newArea.parentId === null) {
    // 添加根节点
    return [...areas, newArea]
  } else {
    // 添加子节点
    return areas.map(area => {
      if (area.id === newArea.parentId) {
        area.children = area.children || []
        area.children.push(newArea)
        area.hasChildren = true
        // 更新父区域名称
        newArea.parentName = area.name
      } else if (area.children && area.children.length > 0) {
        area.children = addArea(area.children, newArea)
      }
      return area
    })
  }
}

// 区域API
export const areaApi = {
  // 获取区域树形列表
  getAreaTree: () => {
    console.log('获取区域树形列表')
    return Promise.resolve({
      code: 200,
      message: 'success',
      data: JSON.parse(JSON.stringify(mockDatabase)) // 深拷贝避免直接修改
    })
  },

  // 创建区域
  createArea: (data: Partial<Area>) => {
    console.log('创建区域:', data)
    return new Promise((resolve) => {
      setTimeout(() => {
        const newId = Math.max(...flattenTree(mockDatabase).map(a => a.id)) + 1
        const now = new Date().toLocaleString()
        
        const newArea: Area = {
          id: newId,
          parentId: data.parentId || null,
          name: data.name || '',
          code: data.code || '',
          level: data.level || 1,
          sort: data.sort || 0,
          status: data.status || 1,
          remark: data.remark || '',
          createTime: now,
          updateTime: now,
          parentName: '',
          hasChildren: false,
          children: []
        }
        
        // 设置父区域名称
        if (newArea.parentId) {
          const parent = findAreaById(mockDatabase, newArea.parentId)
          if (parent) {
            newArea.parentName = parent.name
          }
        }
        
        // 添加到mock数据库
        mockDatabase = addArea(mockDatabase, newArea)
        
        resolve({
          code: 200,
          message: '创建成功',
          data: newArea
        })
      }, 500)
    })
  },

  // 更新区域
  updateArea: (id: number, data: Partial<Area>) => {
    console.log('更新区域:', id, data)
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const existingArea = findAreaById(mockDatabase, id)
        if (!existingArea) {
          reject(new Error('区域不存在'))
          return
        }
        
        // 更新mock数据库
        mockDatabase = updateAreaById(mockDatabase, id, data)
        
        resolve({
          code: 200,
          message: '更新成功',
          data: { id, ...data }
        })
      }, 500)
    })
  },

  // 删除区域
  deleteArea: (id: number) => {
    console.log('删除区域:', id)
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const existingArea = findAreaById(mockDatabase, id)
        if (!existingArea) {
          reject(new Error('区域不存在'))
          return
        }
        
        // 检查是否有子区域
        if (existingArea.children && existingArea.children.length > 0) {
          reject(new Error('该区域下还有子区域，无法删除'))
          return
        }
        
        // 从mock数据库中删除
        mockDatabase = removeAreaById(mockDatabase, id)
        
        resolve({
          code: 200,
          message: '删除成功',
          data: null
        })
      }, 500)
    })
  },

  // 更新区域状态
  updateAreaStatus: (id: number, status: number) => {
    console.log('更新区域状态:', id, status)
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const existingArea = findAreaById(mockDatabase, id)
        if (!existingArea) {
          reject(new Error('区域不存在'))
          return
        }
        
        // 更新状态
        mockDatabase = updateAreaById(mockDatabase, id, { status })
        
        resolve({
          code: 200,
          message: '状态更新成功',
          data: { id, status }
        })
      }, 300)
    })
  }
}

// 导出工具函数供组件使用
export { findAreaById, flattenTree }